#!/usr/bin/bash
pro_base="$(cd `dirname $(readlink -f $0)`;pwd)"        # program base directory. readlink是为了获取脚本的真实路径
pro_root="${pro_base##*/}"                              # 我的程序的根目录名字.   readlink使得ln创建的软链也能正确地执行
pro_name="$(readlink -f $0 | sed 's#^.*/##; s#.sh$##')" # 删除'/'前的路径,删除'.sh'
temp_log=/tmp/${pro_name}.log                   # 往往用在后台执行的程序,比如通过crontab执行的程序
log_dir="/var/log/${pro_root}/${pro_name}"
stdout_log="${log_dir}/${pro_name}.$(date +%Y%m%d).log"


Source(){
    source ${pro_base}/shared/include.sh || exit 1
    Include ${pro_base}/shared/prompt.sh
}

Usage()
{
    echo -e "
    /*
     * 说明：
     * 1.请按需修改 [配置文件]: ${pro_base}/${pro_name}/${pro_name}.conf
     * Usage: 
     * 执行: \033[1mbash $0 {-s|-b|-h|--help}\033[0m
     *                      -s: 设置在crontab每天执行
     *                      -b: 后台执行时使用该option(比如在crond执行)
     */
    "
}                   # $0 总是shell脚本的'路径名/文件名'

Help()              # 若存在 -h 或 --help 选项，则输出 Usage
{
    local i;
    for i
    do
        case $i in
            -h|--help)
                Usage; exit 0;;
            *)
                : ;;
        esac
    done
}

Check_condition(){
    Help "$@"
    [[ $# -ne 1 ]] && Usage && exit 1
    [[ -d "${log_dir}" ]] || Eval_exit "mkdir -p '${log_dir}'"
}

Set_cron(){
    local epel_file epel_flag
if ! type nmon ;then
    epel_file=/etc/yum.repos.d/Centos7-Ali-epel.repo
    epel_flag=0
    [[ -f ${epel_file} ]] && epel_flag=1            # epel_flag=1表示系统已存在${epel_file}
    yum list nmon |egrep -c '^nmon' ||
echo '[Centos7-Ali-epel]
name=Centos7-Ali-epel
baseurl=http://mirrors.aliyun.com/epel/7/$basearch
http://mirrors.aliyuncs.com/epel/7/$basearch
http://mirrors.cloud.aliyuncs.com/epel/7/$basearch
failovermethod=priority
enabled=1
gpgcheck=0' > ${epel_file}
    Eval_exit 'yum -y install nmon'
    [[ ${epel_flag} == 0 ]] && rm -f ${epel_file}   # 删除系统原本不存在的${epel_file}
fi
    if grep -a "bash ${pro_base}/${pro_name}.sh -b" /var/spool/cron/root; then
        PInfo "[计划任务]: ${pro_name}.sh 已存在"
    else
        PInfo "[计划任务]: ${pro_name}.sh 不存在,现在安装任务"
        echo "1 0 * * * bash ${pro_base}/${pro_name}.sh -b" >> /var/spool/cron/root
    fi
    Eval_cont "crontab -l"
}

case $1 in
    -b)
        {
        Source
        Check_condition "$@"
        } &> ${temp_log}
        rm -f ${temp_log}
        
        Eval_exit "nmon -ft -m'${log_dir}'" &>> ${stdout_log}
    ;;
    -s)
        Source
        Check_condition "$@"
        
        Set_cron |& tee -a ${stdout_log}
    ;;
    *)
        Source
        Usage && exit 1
    ;;
esac
